﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using AnchorFinder.Models;
using HtmlAgilityPack;

namespace AnchorFinder.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult ShowUrl()
        {
            return View(new UrlIncludedModel()); 
        }

        [HttpPost]
        public ActionResult ShowUrl(UrlIncludedModel model)
        {
            if (ModelState.IsValid)
            {
               return RedirectToAction("ViewResultUrlList", new { url = model.UrlString });
            }
            return View();
        }

        public ActionResult ViewResultUrlList(string url)
        {
            HttpWebRequest HttpWReq = (HttpWebRequest)WebRequest.Create(url);
            HttpWReq.Method = "GET";
            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            Stream streamResponse = HttpWResp.GetResponseStream();
            StreamReader reader = new StreamReader(streamResponse);
            string response = reader.ReadToEnd();

            ViewBag.UrlListResult = GetUrls(response, url);
            return View();
        }

        public Dictionary<string, List<LinkViewModel>> GetUrls(string inttex, string url)
        {
            string UrlDomen = String.Empty;
            Regex regxdomen = new Regex(@"^(?:\w+://)?([^/?]*)", RegexOptions.IgnoreCase);
            MatchCollection mcurldomen = regxdomen.Matches(url);
            if (mcurldomen.Count != 0)
            {
                UrlDomen = mcurldomen[0].Value;
            }

            Dictionary<string, List<LinkViewModel>> UrlListResult = new Dictionary<string, List<LinkViewModel>>();
            HtmlDocument fulldocument = new HtmlDocument();
            fulldocument.LoadHtml(inttex);
            foreach (HtmlNode link in fulldocument.DocumentNode.SelectNodes("//a[@href]"))
            {
                Regex regxfullurl = new Regex(@"^(https?://)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((/?)|(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$", RegexOptions.IgnoreCase);
                LinkViewModel viewModel = new LinkViewModel();
                if (link != null)
                {
                    var href = String.IsNullOrEmpty(link.Attributes["href"].Value) ? String.Empty : link.Attributes["href"].Value;
                    
                    var innerText = String.IsNullOrEmpty(link.InnerText) ? "Text not found" : link.InnerText;
                    MatchCollection mcfullurl = regxfullurl.Matches(href);
                    if (mcfullurl.Count > 0)
                    {
                        var image = link.ChildNodes.Where<HtmlNode>(a => a.OriginalName.Contains("img")).FirstOrDefault();
                        if (image != null)
                        {
                            viewModel = new LinkViewModel
                            {
                                SourceForImage = image.Attributes["src"].Value,
                                LinkHref = href,
                                LinkTypes = LinkTypes.ImageLink
                            };
                        }
                        else
                        {
                            viewModel = new LinkViewModel
                            {
                                InnerText = innerText,
                                LinkHref = href,
                                LinkTypes = LinkTypes.TextLink
                            };
                        }

                        MatchCollection mcdomen = regxdomen.Matches(href);
                        if (mcdomen.Count != 0)
                        {
                            if (!UrlListResult.ContainsKey(mcdomen[0].Value))
                            {
                                List<LinkViewModel> urls = new List<LinkViewModel>();
                                urls.Add(viewModel);
                                UrlListResult.Add(mcdomen[0].Value, urls);
                            }
                            else
                            {
                                UrlListResult[mcdomen[0].Value].Add(viewModel);
                            }
                        }
                    }
                    else
                    {
                        if (!String.IsNullOrEmpty(UrlDomen))
                        {
                            MatchCollection mcfullurlsum = regxfullurl.Matches(UrlDomen + href);
                            if (mcfullurlsum.Count > 0)
                            {
                                var image = link.ChildNodes.Where<HtmlNode>(a => a.OriginalName.Contains("img")).FirstOrDefault();
                                if (image != null)
                                {
                                    viewModel = new LinkViewModel
                                    {
                                        SourceForImage = image.Attributes["src"].Value,
                                        LinkHref = UrlDomen + href,
                                        LinkTypes = LinkTypes.ImageLink
                                    };
                                }
                                else
                                {
                                    viewModel = new LinkViewModel
                                    {
                                        InnerText = innerText,
                                        LinkHref = UrlDomen + href,
                                        LinkTypes = LinkTypes.TextLink
                                    };
                                }
                                if (!UrlListResult.ContainsKey(UrlDomen))
                                {
                                    List<LinkViewModel> urls = new List<LinkViewModel>();
                                    urls.Add(viewModel);
                                    UrlListResult.Add(UrlDomen, urls);
                                }
                                else
                                {
                                    UrlListResult[UrlDomen].Add(viewModel);
                                }
                            }
                        }
                        else
                        {
                            viewModel = new LinkViewModel
                            {
                                InnerText = innerText,
                                LinkTypes = LinkTypes.NotFullUrl
                            };

                            string domainNotFound = "Domain Not Found";
                            if (!UrlListResult.ContainsKey(domainNotFound))
                            {
                                List<LinkViewModel> urls = new List<LinkViewModel>();
                                urls.Add(viewModel);
                                UrlListResult.Add(domainNotFound, urls);
                            }
                            else
                            {
                                UrlListResult[domainNotFound].Add(viewModel);
                            }
                        }
                    }
                }
            }
            return UrlListResult;
        }
    }
}
